package com.xzc.shopping.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzc.shopping.common.BaseResponse;
import com.xzc.shopping.common.ErrorCode;
import com.xzc.shopping.common.ResultUtils;
import com.xzc.shopping.mapper.ThumbMapper;
import com.xzc.shopping.model.result.ThumbResult;
import com.xzc.shopping.model.domain.Thumb;
import com.xzc.shopping.service.ProductService;
import com.xzc.shopping.service.ThumbService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
* @author Administrator
* @description 针对表【thumb】的数据库操作Service实现
* @createDate 2025-02-26 11:03:25
*/
@Service
public class ThumbServiceImpl extends ServiceImpl<ThumbMapper, Thumb>
implements ThumbService {

    @Resource
    private  ProductService productService;

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务注解
    public BaseResponse<ThumbResult> toggleThumb(Integer userId, Integer productId) {
        try {
            // 1. 检查用户是否已点赞
            boolean isThumbed = this.existsByUserIdAndProductId(userId, productId);

            // 2. 执行点赞/取消操作
//            boolean operationSuccess;
//            if (isThumbed) {
//                operationSuccess = this.removeByUserIdAndProductId(userId, productId);
//            } else {
//                Thumb thumb = new Thumb();
//                thumb.setUserId(userId);
//                thumb.setProductId(productId);
//                operationSuccess = this.save(thumb);
//            }

            // 3. 操作失败处理


            // 4. 更新商品点赞数（注意：此处需要确保原子操作）
            boolean operationSuccess;
            if (isThumbed) {
               operationSuccess = productService.decrementThumbCount(productId);
                deleteByUserIdAndProductId(userId, productId);
            } else {
                operationSuccess =productService.incrementThumbCount(productId);
                saveByUserIdAndProductId(userId, productId);
            }

            if (!operationSuccess) {
                return ResultUtils.error(ErrorCode.UPDATE_ERROR, "更新失败");
            }

            // 5. 获取最新点赞数（必须重新查询确保数据准确性）
            Integer latestThumbCount = productService.getThumbCount(productId);

            // 6. 构建返回结果
            ThumbResult result = new ThumbResult();
            result.setIsThumbed(!isThumbed); // 操作后的状态
            result.setThumbCount(latestThumbCount);
            return ResultUtils.success(result);

        } catch (DuplicateKeyException e) {
            // 处理重复点赞（防止并发请求）
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "不能重复点赞");
        } catch (Exception e) {
            log.error("点赞操作异常：", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统异常");
        }
    }


    /**
     * 检查用户是否已点赞
     */
    public boolean existsByUserIdAndProductId(Integer userId, Integer productId) {
        QueryWrapper<Thumb> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("product_id", productId);
        return this.count(queryWrapper) > 0;
    }



    /**
     * 删除用户的点赞记录
     * @param userId
     * @param productId
     * @return
     */
    public boolean deleteByUserIdAndProductId(Integer userId, Integer productId) {
        QueryWrapper<Thumb> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("product_id", productId);
        return this.remove(queryWrapper);

    }

    /**
     * 增加用户的点赞记录
     * @param userId
     * @param productId
     * @return
     */
    public boolean saveByUserIdAndProductId(Integer userId, Integer productId) {
        Thumb thumb = new Thumb();
        thumb.setUserId(userId);
        thumb.setProductId(productId);
        return this.save(thumb);

    }

    /**
     * 根据用户ID和商品ID删除点赞记录
     */
    public boolean removeByUserIdAndProductId(Integer userId, Integer productId) {
        QueryWrapper<Thumb> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("product_id", productId);
        return this.remove(queryWrapper);
    }


}
